using System;
using System.Collections.Generic;

namespace ZyGame.Subscribes
{
    class SubjectManager : Singleton<SubjectManager>
    {
        private Dictionary<Type, List<ISubscribe>> _subs = new Dictionary<Type, List<ISubscribe>>();

        public void Add<T>(ISubscribe subscribe)
        {
            if (!_subs.TryGetValue(typeof(T), out List<ISubscribe> subscribes))
            {
                _subs.Add(typeof(T), subscribes = new List<ISubscribe>());
            }

            subscribes.Add(subscribe);
        }

        public void Remove(ISubscribe subscribe)
        {
            foreach (var VARIABLE in _subs.Values)
            {
                VARIABLE.Remove(subscribe);
            }
        }

        public void Clear<T>()
        {
            if (!_subs.TryGetValue(typeof(T), out List<ISubscribe> list))
            {
                return;
            }

            list.Clear();
            _subs.Remove(typeof(T));
        }

        public void Execute<T>(T args)
        {
            if (!_subs.TryGetValue(typeof(T), out List<ISubscribe> list))
            {
                return;
            }

            foreach (var item in list)
            {
                try
                {
                    item.Execute(args);
                }
                catch (Exception e)
                {
                    Client.Console.WriteLine(e);
                    throw;
                }
            }
        }
    }
}